package com.ciwong.epaper.modules.epaper.adapter;

import android.content.Context;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.me.ui.LoadingFileActivity;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.util.download.ProgressCircle;
import com.ciwong.libs.utils.CWLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * CatalogActivity相关adapter
 * <p/>
 * Created by res-yinxue on 2016/7/8.
 */
public class CatalogAdapter1 extends BaseExpandableListAdapter {

    /**
     * 上下文
     */
    private Context mContext;

    private LayoutInflater mInflater;

    private List<CatalogueInfo> catalogueInfos;

    List<DownLoadInfo> mDownLoadInfoList = new ArrayList<>();

    private int LIST_TYPE;

    private boolean isHideDownloadBtn = false;// 是否隐藏下载按钮

    private boolean noMore = true;//是否有多级目录
    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    private CatalogAdapter2 treeViewAdapter;

    private SecondGroupClick secondGroupClick;

    private ThirdGroupClick thirdGroupClick;

    public interface SecondGroupClick {
        void SecondGroupClick(CatalogueInfo catalogueInfo);
    }

    public interface ThirdGroupClick {
        void ThirdGroupClick(CatalogueInfo catalogueInfo);
    }

    private DownLoadInfo downLoadInfo;

    private String mBookId;

    private Handler mHandler = new Handler();

    /**
     * 构造器
     */
    public CatalogAdapter1(Context context,
                           List<CatalogueInfo> catalogueInfos,
                           boolean isHideDownloadBtn,
                           int type, SecondGroupClick secondGroupClick, ThirdGroupClick thirdGroupClick) {
        this.mContext = context;
        this.secondGroupClick = secondGroupClick;
        this.thirdGroupClick = thirdGroupClick;
        this.catalogueInfos = catalogueInfos;
        this.isHideDownloadBtn = isHideDownloadBtn;
        this.LIST_TYPE = type;
        mInflater = LayoutInflater.from(mContext);
    }


    @Override
    public int getGroupCount() {

        return catalogueInfos == null ? 0 : catalogueInfos.size();

    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return catalogueInfos == null ? 0 : catalogueInfos.get(groupPosition).getChildren().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return catalogueInfos == null || catalogueInfos.isEmpty() ? null : catalogueInfos.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return catalogueInfos == null || catalogueInfos.isEmpty() ? null : catalogueInfos.get(groupPosition).getChildren().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    /**
     * 三级树结构中的首层
     */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.adapter_threedirectory_item, null);
            holder.nameTV = (TextView) convertView.findViewById(R.id.name_tv);
            holder.progressCircle = (ProgressCircle) convertView
                    .findViewById(R.id.directory_item_min_pb);
            holder.horPb = (ProgressBar) convertView.findViewById(R.id.directory_item_hor_pb);
            holder.sizeTV = (TextView) convertView.findViewById(R.id.size_tv);
            holder.speedTV = (TextView) convertView.findViewById(R.id.down_speed__tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.nameTV.setGravity(Gravity.CENTER_VERTICAL);
        holder.nameTV.setText(catalogueInfos.get(groupPosition).getName());
        //true:没有子目录 false:有子目录
        noMore = onlyOneCatalogue(catalogueInfos);
        setParams(convertView, noMore);
        CatalogueInfo info = (CatalogueInfo) getGroup(groupPosition);
        int count = info.getChildren().size();
        downLoadInfo = getDownLoadInfo(info);
        //没有子目录，显示该item隐藏的控件

        if (downLoadInfo != null) {
            if (null != downLoadInfo) {
                if (count == 0) {
                    holder.progressCircle.setVisibility(View.VISIBLE);
                    holder.horPb.setVisibility(View.VISIBLE);
                    dealCircleProgress(downLoadInfo, holder.horPb, holder.progressCircle, holder.sizeTV, holder.speedTV);
                } else {
                    holder.progressCircle.setVisibility(View.GONE);
                    holder.horPb.setVisibility(View.GONE);
                }
            }
        }
        return convertView;
    }

    /**
     * 三层树结构中的第二层是一个ExpandableListView
     */
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        CatalogueInfo cInfo = (CatalogueInfo) getGroup(groupPosition);
        if (cInfo.getChildren().size() == 0 || null == cInfo.getChildren()) {
            return null;
        }
        final ExpandableListView expandableListView = getExpandableListView();
        //隐藏滚动条
        expandableListView.setVerticalScrollBarEnabled(false);
        //创建CatalogAdapter2对象
        treeViewAdapter = new CatalogAdapter2(mContext, isHideDownloadBtn, LIST_TYPE);
        //临时变量取得TreeViewAdapter的CatalogueInfo集合，可为空
        List<CatalogueInfo> tmp = treeViewAdapter.getCatalogueInfo();
        //获得一级目录中List集合，用于二级目录
        final CatalogueInfo catalogueInfo = (CatalogueInfo) getChild(groupPosition, childPosition);
        tmp.add(catalogueInfo);
        //把二级List传给给TreeViewAdapter
        treeViewAdapter.updateCatalogueInfo(tmp);
        treeViewAdapter.setDownLoadInfoList(mDownLoadInfoList);
        expandableListView.setAdapter(treeViewAdapter);

        //treeViewAdapter.setDownLoadInfoList(mDownLoadInfoList);

        //关键点：取得选中的二级树形菜单的父子节点,结果返回给外部回调函数
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                thirdGroupClick.ThirdGroupClick(catalogueInfo.getChildren().get(childPosition));
                return true;
            }
        });

        //第二级菜单展开时通过获取节点数来设置第三级菜单的大小
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {

                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        (catalogueInfo.getChildren().size() + 1) * (int) mContext.getResources().getDimension(R.dimen.book_list_height));
                expandableListView.setLayoutParams(lp);
            }
        });


        //不可收缩
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                secondGroupClick.SecondGroupClick(catalogueInfo);
                return true;
            }
        });

        //展开列表
        for (int i = 0; i < tmp.size(); i++) {
            expandableListView.expandGroup(i);
        }

        return expandableListView;
    }

    private static class ViewHolder {
        TextView nameTV, sizeTV, speedTV;

        ProgressBar horPb;

        ProgressCircle progressCircle;
    }


    /**
     * 创建第二层的ExpandableListView
     */
    public ExpandableListView getExpandableListView() {
        int itemHeight = (int) mContext.getResources().getDimension(R.dimen.book_list_height);
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        ExpandableListView superTreeView = new ExpandableListView(mContext);
        superTreeView.setLayoutParams(lp);
        superTreeView.setGroupIndicator(null);
        return superTreeView;
    }

    /**
     * 设置属性
     *
     * @param view
     */
    public void setParams(View view, boolean more) {
        /*int itemHeight = (int) mContext.getResources().getDimension(R.dimen.book_list_height);
        RelativeLayout relativeLayout = (RelativeLayout) view;
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, itemHeight);
        relativeLayout.setLayoutParams(lp);
        relativeLayout.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);*/
        if (!more) {
           // relativeLayout.setBackgroundColor(Color.parseColor("#e8e8e8"));
            view.setBackgroundColor(Color.parseColor("#e8e8e8"));

        }

    }

    /**
     * 判断集合中是否全部为一级目录
     */
    public boolean onlyOneCatalogue(List<CatalogueInfo> catalogueInfos) {
        for (CatalogueInfo info : catalogueInfos) {
            noMore = info.getChildren().size() == 0 ? true : false;
            if (!noMore) {
                return false;
            }
        }
        return true;
    }


    private DownLoadInfo getDownLoadInfo(CatalogueInfo curInfo) {
        DownLoadInfo downLoadInfo = null;
        if (mDownLoadInfoList != null && mDownLoadInfoList.size() > 0) {
            for (int i = 0; i < mDownLoadInfoList.size(); i++) {
                if (mDownLoadInfoList.get(i).getChapterId().equals(curInfo.getId())) {
                    downLoadInfo = mDownLoadInfoList.get(i);
                    break;
                }
            }
        }
        return downLoadInfo;
    }


    private void dealCircleProgress(final DownLoadInfo info, ProgressBar horPb,
                                    final ProgressCircle progressCircle,
                                    final TextView sizeText,
                                    final TextView speedText) {
//        if (isHideDownloadBtn || (LIST_TYPE == CatalogActivity.LIST_COMPLETED
//                && info.getStatus() == DownloadStatus.STATUS_COMPLETED)) {
//            progressCircle.setVisibility(View.GONE);
//            sizeText.setVisibility(View.GONE);
//            speedText.setVisibility(View.GONE);
//            return;
//        }
        progressCircle.setIsError(false);
        switch (info.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
//                horPb.setProgress(0);
                progressCircle.updateDownloadProgress(0);
                progressCircle.setIsError(TextUtils.isEmpty(info.getUrl()));
                progressCircle.initToNormal();
                break;
            case DownloadStatus.STATUS_LOADING:
//                horPb.setProgress(0);
                progressCircle.initToLoading();
                //文件大小
//                sizeText.setVisibility(View.VISIBLE);
//                speedText.setVisibility(View.VISIBLE);
//                sizeText.setText(info.getSize() + " MB");
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoadInfo currentInfo = DownLoad.getInstance()
                        .getCurrentBean(info);
                if (currentInfo != null) {
                    info.setProgress(currentInfo.getProgress());
                }

                //实时下载的网速
//                long downSpeed = getNetSpeed();
//                speedText.setText(downSpeed / 1024 + " kb/s");
//
//                horPb.setProgress(info.getProgress());
                progressCircle
                        .updateDownloadProgress(info.getProgress() / 100f);
                break;
            case DownloadStatus.STATUS_COMPLETED:
                CWLog.e("TAT", "C1 ====== DownloadStatus.STATUS_COMPLETED !!!!!!!!!");
                if (LIST_TYPE == CatalogueInfo.LIST_ALL) {
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_ALL" + packageDir);
                    if (new File(packageDir).exists()) {
//                        horPb.setProgress(0);
                        progressCircle.initToCompleted();
                    }
//                    else {
//                        info.setProgress(0);
//                        DownLoad.getInstance().pauseTask(info);
//                    }
//                    speedText.setVisibility(View.GONE);
//                    sizeText.setVisibility(View.GONE);
                } else if (LIST_TYPE == CatalogueInfo.LIST_DOWNLOADING) {
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_DOWNLOADING" + packageDir);
                    if (new File(packageDir).exists()) {
                        catalogueInfos.remove(info);
                        if (mContext instanceof LoadingFileActivity) {
                            ((LoadingFileActivity) mContext).showLlEmpty();
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                notifyDataSetChanged();
                            }
                        }, 10);
                    }
//                    else {
//                        DownLoad.getInstance().stopTask(info);
//                    }
                }
                break;
            case DownloadStatus.STATUS_PAUSE:
                horPb.setProgress(info.getProgress());
                progressCircle.initToPause();
                break;
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
                horPb.setProgress(0);
                Log.i("se7en", this.getClass().getName()
                        + "DownloadStatus.STATU_FAILED" + info.getChapterName());
                progressCircle.initToFAILED();
                break;
            case DownloadStatus.STATUS_UPZIPING:
                CWLog.e("TAT", "C1 ====== DownloadStatus.STATUS_UPZIPING");
                horPb.setProgress(100);
                progressCircle.initToLoading();
                break;
        }
    }

    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return traffic_data;
    }


    /**
     * 设置数据
     */
    public void setAll(List<CatalogueInfo> catalogueInfos) {
        if (catalogueInfos != null) {
            this.catalogueInfos.clear();
            this.catalogueInfos.addAll(catalogueInfos);

        }
    }

    /**
     * 添加数据
     */
    public void addAll(List<CatalogueInfo> catalogueInfos, boolean isRefulsh) {
        if (this.catalogueInfos == null) {
            this.catalogueInfos = new ArrayList<CatalogueInfo>();
        }
        if (catalogueInfos != null) {
            this.catalogueInfos = catalogueInfos;
            if (isRefulsh) {
                notifyDataSetChanged();
            }
        }
    }

    /**
     * 删除数据
     */
    public void removeAll() {
        if (this.catalogueInfos != null) {
            this.catalogueInfos.clear();
            // notifyDataSetChanged();

        }
    }


    public void setDownLoadInfoList(List<DownLoadInfo> downLoadInfoList) {
        if (null != downLoadInfoList && downLoadInfoList.size() > 0) {
            mDownLoadInfoList = downLoadInfoList;
        }

    }

}
